// 从 doc/训练经验.md 读取“训练10小时总经验”，反推每小时与标准经验，并写入 level_experience
// 规则：
// - total10h = 文档第3列
// - perHour = total10h / (10 * 1.1) = total10h / 11
// - multiplier: 1-40:150, 41-70:200, 71-160:300
// - standardExp = perHour / multiplier
// 写入：level_experience(level, experience) 存 standardExp（四舍五入取整）

const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const config = require('./database-config.js');

function getMultiplier(level) {
    if (level >= 1 && level <= 40) return 150;
    if (level >= 41 && level <= 70) return 200;
    return 300;
}

async function main() {
    const docPath = path.join(__dirname, 'doc/训练经验.md');
    const raw = fs.readFileSync(docPath, 'utf8');
    const lines = raw.split(/\r?\n/);

    const rows = [];
    for (const line of lines) {
        if (!line || line.startsWith('#') || line.startsWith('等级')) continue;
        const parts = line.split(',');
        if (parts.length < 3) continue;
        const level = parseInt(parts[0], 10);
        const total10h = parseInt(parts[2], 10);
        if (Number.isFinite(level) && Number.isFinite(total10h) && level >= 1 && level <= 160) {
            rows.push({ level, total10h });
        }
    }

    const conn = await mysql.createConnection(config.source);
    try {
        console.log(`🔧 准备导入 level_experience，共 ${rows.length} 条`);
        let upserts = 0;
        for (const r of rows) {
            const perHour = Math.floor(r.total10h / 11); // 每小时经验
            const m = getMultiplier(r.level);
            const standard = Math.max(1, Math.round(perHour / m)); // 标准经验（最小1）
            await conn.execute(
                `INSERT INTO level_experience (level, experience, created_at, updated_at)
         VALUES (?, ?, NOW(), NOW())
         ON DUPLICATE KEY UPDATE experience=VALUES(experience), updated_at=NOW()`,
                [r.level, standard]
            );
            upserts += 1;
        }
        console.log(`✅ 导入完成，写入/更新 ${upserts} 条`);
    } catch (e) {
        console.error('❌ 导入失败:', e.message || e);
        process.exitCode = 1;
    } finally {
        await conn.end();
    }
}

if (require.main === module) {
    main();
}




